package com.yuji.aacar.tools;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Xml;
import android.view.Display;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.yuji.aacar.core.cores.utils.CorePersistenceUtil;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.net.config.HttpConfig;

import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.yuji.aacar.core.cores.utils.CoreDeviceUtil.getImei;
import static com.yuji.aacar.core.cores.utils.CoreDeviceUtil.newRandomUUID;
import static com.yuji.aacar.core.cores.utils.CoreSizeUtil.getScreenHeight;


/**
 */
public class Tools {


    /**
     * @param mobiles
     * @return
     * @description 手机号设定输入只能为11位纯数字，且开头数字必须为： （电信）133、153、180、181、189；
     * （移动）134、135
     * 、136、137、138、139、147、150、151、152、157、158、159、182、183
     * 、184、187、188； （联通）130、131、132、145、155、156、185、186。
     * 手机号限制需要可以根据实际情况进行修改，如新增手机号段190，限制也需要做对应变化。
     * 手机号码校验适用于个人app所有需要输入手机号码的文本框，具体提示语见文本框说明。
     */
    public static boolean isPhoneNumberValid(String mobiles) {
        //        String exprssion = "^((13[0-9])|(145)|(147)|(15[^4,\\D])|(18[0-9]))\\d{8}$";
        //        Pattern p = Pattern.compile(exprssion);
        //
        //        if (p == null) {
        //            return false;
        //        }
        //        Matcher m = p.matcher(mobiles);
        //        return m.matches();
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        }
        if (mobiles.length() == 11 && mobiles.startsWith("1")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isCarNo(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern
                .compile("^[京,津,渝,沪,冀,晋,辽,吉,黑,苏,浙,皖,闽,赣,鲁,豫,鄂,湘,粤,琼,川,贵,云,陕,秦,甘,陇,青,台,内蒙古,桂,宁,新,藏,澳,军,海,航,警][a-zA-Z][0-9,a-zA-Z]{5}$"); // 验证车牌号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    public static boolean isPassWordValid(String password) {
        if (TextUtils.isEmpty(password)) {
            return false;
        }
        if (password.length() >= 6) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 是否为账号规范
     * 如：
     * 6~16个字符，可使用字母、数字、下划线，需以字母开头
     *
     * @param text
     * @return
     * @author luman
     */
    public static boolean isAccountStandard(String text) {
        //不能包含中文
        if (hasChinese(text)) {
            return false;
        }

        /**
         * 正则匹配：
         * [a-zA-Z]:字母开头
         * \\w :可包含大小写字母，数字，下划线,@
         * {5,15} 5到15位，加上开头字母  字符串长度6到16
         */
        String format = "^[a-zA-Z0-9]{6,16}$";
        if (text.matches(format)) {
            return true;
        }
        return false;
    }


    /**
     * 是否为密码规范
     *
     * @param text
     * @return
     * @author luman
     */
    public static boolean isPasswordStandard(String text) {


        //不能包含中文
        if (hasChinese(text)) {
            return false;
        }


        /**
         * 正则匹配
         * \\w{6,18}匹配所有字母、数字、下划线 字符串长度6到18（不含空格）
         */
        String format = "\\w{6,18}+";
        if (text.matches(format)) {
            return true;
        }
        return false;
    }


    /**
     * 中文识别
     *
     * @author luman
     */
    public static boolean hasChinese(String source) {
        String reg_charset = "([\\u4E00-\\u9FA5]*+)";
        Pattern p = Pattern.compile(reg_charset);
        Matcher m = p.matcher(source);
        boolean hasChinese = false;
        while (m.find()) {
            if (!"".equals(m.group(1))) {
                hasChinese = true;
            }
        }
        return hasChinese;
    }

    /**
     * 判断是否有网络
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * 关闭键盘
     *
     * @param context
     * @param v
     */
    public static void closeKeyBroad(Context context, View v) {
        if (v != null) {
            if (v.getWindowToken() != null) {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 数字金额大写转换，思想先写个完整的然后将如零拾替换成零
     * 要用到正则表达式
     */
    public static String digitUppercase(double n) {
        String fraction[] = {"角", "分"};
        String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String unit[][] = {{"元", "万", "亿"},
                {"", "拾", "佰", "仟"}};

        String head = n < 0 ? "负" : "";
        n = Math.abs(n);

        String s = "";
        for (int i = 0; i < fraction.length; i++) {
            s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
        }
        if (s.length() < 1) {
            s = "整";
        }
        int integerPart = (int) Math.floor(n);

        for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
            String p = "";
            for (int j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[integerPart % 10] + unit[1][j] + p;
                integerPart = integerPart / 10;
            }
            s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
        }
        return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
    }


    public static String getLocalHostIp() {
        String ipaddress = "";
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            // 遍历所用的网络接口
            while (en.hasMoreElements()) {
                NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
                Enumeration<InetAddress> inet = nif.getInetAddresses();
                // 遍历每一个接口绑定的所有ip
                while (inet.hasMoreElements()) {
                    InetAddress ip = inet.nextElement();
                    if (!ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                        return ip.getHostAddress();
                    }
                }

            }
        } catch (SocketException e) {
            Log.e("feige", "获取本地ip地址失败");
        }
        return ipaddress;

    }

    public static String getWifiIp(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);
        return ip;
    }

    /**
     * 手机是否连接网络
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isConnected();
            }
        }
        return false;
    }

    private static String intToIp(int i) {

        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }


    /**
     * 获得屏幕宽
     *
     * @param context
     * @return
     */
    public static int getDisplayWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    /**
     * 获得屏幕高
     *
     * @param context
     * @return
     */
    public static int getDisplayHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }


    /**
     * @param context
     * @return metadata 的bundle对象
     * 获取manifest配置文件
     */
    public static Bundle getMetaData(Context context) {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(context
                    .getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo != null && applicationInfo.metaData != null) {
                return applicationInfo.metaData;
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(
                    "name not found", e);
        }
        return null;
    }

    /**
     * @param context
     * @param srcSize
     * @param isHorizontal
     * @return 获取当前屏幕相对与设计稿尺寸的值
     */
    public static int getPercentSize(Context context, int srcSize, boolean isHorizontal) {
        if (srcSize == -1 || srcSize == -2) {
            return srcSize;
        }
        if (isHorizontal) {
            return srcSize * getDisplayWidth(context) / getMetaData(context).getInt("design_width");
        } else {
            return srcSize * getDisplayHeight(context) / getMetaData(context).getInt("design_height");
        }
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    //    public static int dip2px(float dipValue) {
    ////        return dip2px(CheckerApplication.appContext, dipValue);
    //    }

    /**
     * @param token
     * @param userID 保存token userID
     */
    public static void saveToken(String token, String userID) {
        CorePersistenceUtil.setParam("TOKEN_KEY", token);
        CorePersistenceUtil.setParam("USER_ID", userID);
        LogUtil.e("--saveToken--token--", token);
        LogUtil.e("--saveToken--userID--", userID);
        HttpConfig.setToken(token);
        HttpConfig.setUserId(userID);
    }

    /**
     * @return 0 是token 1 是userID
     * 获取token userID
     */
    public static String[] getToken() {
        String[] s = new String[2];
        s[0] = (String) CorePersistenceUtil.getParam("TOKEN_KEY", "");
        s[1] = (String) CorePersistenceUtil.getParam("USER_ID", "");
        return s;
    }


    /**
     * 获得系统版本号
     *
     * @return
     */
    public static int getAndroidOSVersion() {
        int osVersion;
        try {
            osVersion = Integer.valueOf(Build.VERSION.SDK);
        } catch (NumberFormatException e) {
            osVersion = 0;
        }
        return osVersion;
    }

    /**
     * 获得uuuserid
     *
     * @param context
     * @return
     */
    public static String getuuUserId(Context context) {
        SharedPreferences sharedPrefs = context.getSharedPreferences("client_preferences",
                Context.MODE_PRIVATE);
        String uuid = getImei(context);
        if (TextUtils.isEmpty(uuid)) {
            uuid = sharedPrefs.getString("uu_user_id", "");//
        }
        if (TextUtils.isEmpty(uuid)) {
            uuid = newRandomUUID();
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putString("uu_user_id",
                    uuid);
            editor.commit();
        }
        return uuid;
    }

    /**
     * 获得当前版本号
     *
     * @param context
     * @return
     */
    public static String getAppVersionName(Context context) {
        try {
            PackageInfo pkgInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            if (pkgInfo != null) {
                return pkgInfo.versionName;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 利用反射获取状态栏高度
     *
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        try {
            //获取状态栏高度的资源id
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = context.getResources().getDimensionPixelSize(resourceId);
            }
        } catch (Exception e) {
            result = Tools.dip2px(context, 20);
        } finally {
            return result;
        }
    }

    /**
     * @param root         最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    public static void controlKeyboardLayout(Context context, final View root, final View scrollToView) {
        // 注册一个回调函数，当在一个视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变时调用这个回调函数。
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                // 获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                // 当前视图最外层的高度减去现在所看到的视图的最底部的y坐标
                int rootInvisibleHeight = root.getRootView()
                        .getHeight() - rect.bottom - Tools.getBottomStatusHeight(context);
                LogUtil.i("tag", "最外层的高度" + root.getRootView().getHeight());
                // 若rootInvisibleHeight高度大于100，则说明当前视图上移了，说明软键盘弹出了
                if (rootInvisibleHeight > 100) {
                    //软键盘弹出来的时候
                    int[] location = new int[2];
                    // 获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    // 计算root滚动高度，使scrollToView在可见区域的底部
                    int srollHeight = (location[1] + scrollToView
                            .getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    // 软键盘没有弹出来的时候
                    root.scrollTo(0, 0);
                }
            }
        });
    }

    /**
     * 获取 虚拟按键的高度
     *
     * @param context
     * @return
     */
    public static int getBottomStatusHeight(Context context) {
        int totalHeight = getDpi(context);

        int contentHeight = getScreenHeight(context);

        return totalHeight - contentHeight;
    }


    //获取屏幕原始尺寸高度，包括虚拟功能键高度
    public static int getDpi(Context context) {
        int dpi = 0;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, displayMetrics);
            dpi = displayMetrics.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }

    public static String autoSplitText(final TextView tv) {
        final String rawText = tv.getText().toString(); //原始文本
        final Paint tvPaint = tv.getPaint(); //paint，包含字体等信息
        final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度

        //将原始文本按行拆分
        String[] rawTextLines = rawText.replaceAll("\r", "").split("\n");
        StringBuilder sbNewText = new StringBuilder();
        for (String rawTextLine : rawTextLines) {
            if (tvPaint.measureText(rawTextLine) <= tvWidth) {
                //如果整行宽度在控件可用宽度之内，就不处理了
                sbNewText.append(rawTextLine);
            } else {
                //如果整行宽度超过控件可用宽度，则按字符测量，在超过可用宽度的前一个字符处手动换行
                float lineWidth = 0;
                for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
                    char ch = rawTextLine.charAt(cnt);
                    lineWidth += tvPaint.measureText(String.valueOf(ch));
                    if (lineWidth <= tvWidth) {
                        sbNewText.append(ch);
                    } else {
                        sbNewText.append("\n");
                        lineWidth = 0;
                        --cnt;
                    }
                }
            }
            sbNewText.append("\n");
        }

        //把结尾多余的\n去掉
        if (!rawText.endsWith("\n")) {
            sbNewText.deleteCharAt(sbNewText.length() - 1);
        }

        return sbNewText.toString();
    }


    public static Map<String, String> decodeXml(String content) {

        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("Simon", "----" + e.toString());
        }
        return null;

    }


    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public static void diallPhone(Context context, String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }


    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNum 电话号码
     */
    public void callPhone(Context context, String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }

    /**
     * 调起系统发短信功能
     *
     * @param phoneNumber
     * @param message
     */
    public static void sendSMSTo(Context context, String phoneNumber, String message) {
        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
            intent.putExtra("sms_body", message);
            context.startActivity(intent);
        }

    }
}